package com.myjoje.service.tencent;

import com.myjoje.base.BaseService;
import com.myjoje.bean.system.FileBean;
import com.myjoje.config.shiro.ShiroUtil;
import com.myjoje.jpa.FileJpa;
import com.myjoje.util.Message;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 腾讯云对象存储
 */
@Service
public class CosService extends BaseService {

    @Value("${tencent.cos.bucket-name}")
    private String bucketName;

    @Value("${tencent.cos.bucket-url}")
    private String bucketUrl;

    @Autowired
    private COSClient cosClient;

    @Autowired
    private FileJpa fileJpa;

    /**
     * 上传文件
     *
     * @param multipartFile
     * @return
     */
    public Message uploadFile(MultipartFile multipartFile) throws Exception {
        String filename = multipartFile.getOriginalFilename();

        //设置上传路径
        String key = "/" + ShiroUtil.getMd5(getYear()) + "/" +
                ShiroUtil.getMd5(getMonth()) + "/" + get32UUID();

        ExecutorService threadPool = Executors.newFixedThreadPool(32);
        // 传入一个threadpool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池。
        TransferManager transferManager = new TransferManager(cosClient, threadPool);
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(multipartFile.getContentType());
        objectMetadata.setContentLength(multipartFile.getSize());
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,
                multipartFile.getInputStream(), objectMetadata);
        // 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
        putObjectRequest.setStorageClass(StorageClass.Standard);
        Upload upload = transferManager.upload(putObjectRequest);
        UploadResult uploadResult = upload.waitForUploadResult();
        transferManager.shutdownNow();
        //ETag 全称 Entity Tag，是对象被创建时标识对象内容的信息标签，可用于检查对象的内容是否发生变化
        String eTag = uploadResult.getETag();
        if (isNotEmpty(eTag)) {
//            //生成公有读 Bucket（匿名可读），不需要签名的链接
//            GeneratePresignedUrlRequest req =
//                    new GeneratePresignedUrlRequest(bucketName, key, HttpMethodName.GET);
//            URL url = cosClient.generatePresignedUrl(req);
            //将上传信息保存到数据库
            FileBean bean = new FileBean();
            bean.setCreateTime(getDateTime());
            bean.setFileName(filename);
            //访问路径
            bean.setAccessPath(bucketUrl + key);
            bean.setFileSize(String.valueOf(multipartFile.getSize()));
            bean.setFileType(multipartFile.getContentType());
            String currentUserId = getCurrentUserId();
            bean.setCreateUser(currentUserId);
            fileJpa.save(bean);
            return Message.success("上传成功", bean);
        }
        return Message.success("上传失败");
    }

    public void deleteObject(String accessPath) {
        cosClient.deleteObject(bucketName, accessPath.replace(bucketUrl, ""));
    }
}
